// lib/app/config/route_observer.dart
import 'package:flutter/material.dart';

class CustomRouteObserver extends NavigatorObserver {
  final Map<String, VoidCallback> _disappearCallbacks = {};
  final Map<String, VoidCallback> _appearCallbacks = {};

  void onPageWillDisappear(String routeName, VoidCallback callback) {
    _disappearCallbacks[routeName] = callback;
  }

  void onPageDidAppear(String routeName, VoidCallback callback) {
    _appearCallbacks[routeName] = callback;
  }

  @override
  void didPop(Route route, Route? previousRoute) {
    _triggerCallbacks(previousRoute?.settings.name, route.settings.name);
  }

  @override
  void didPush(Route route, Route? previousRoute) {
    _triggerCallbacks(route.settings.name, previousRoute?.settings.name);
  }

  void _triggerCallbacks(String? currentRoute, String? previousRoute) {
    // 触发新页面 appear
    if (currentRoute != null && _appearCallbacks.containsKey(currentRoute)) {
      _appearCallbacks[currentRoute]!();
    }

    // 触发旧页面 disappear
    if (previousRoute != null &&
        _disappearCallbacks.containsKey(previousRoute)) {
      _disappearCallbacks[previousRoute]!();
    }
  }
}

// 全局单例
final customRouteObserver = CustomRouteObserver();
